package com.romanito.netreco;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.widget.Toast;

public class NetReco extends Activity {
	
	private boolean bFinished = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try {
			ProgressDialog.show(this, 
					getResources().getText(R.string.app_name), 
					getResources().getText(R.string.reconnecting));			
			reconnect();
		}
		catch (Exception e) {
			Toast.makeText(this, e.getMessage(), 4000);
		}
	}

	private void reconnect() {
		// Sets a broadcast receiver to detect when Airplane mode is changed 
		IntentFilter intentFilter = new IntentFilter("android.intent.action.SERVICE_STATE");
		BroadcastReceiver receiver = new BroadcastReceiver() {
		      @Override
		      public void onReceive(Context context, Intent intent) {
		    	  if (isAirplaneModeOn()) {
		    		  SystemClock.sleep(1000);
		    		  setAirPlaneMode(false);
		    	  }
		    	  else {;
			    	  if (!bFinished) {
			    		  bFinished = true;
			    		  finish();
			    	  }
		    	  }
		      }
		};
		getApplicationContext().registerReceiver(receiver, intentFilter);
		
		if (isAirplaneModeOn()){
			setAirPlaneMode(false);
		}
		else {
			setAirPlaneMode(true);
		}
	}
	
	// Returns true is Airplane mode is on
	private boolean isAirplaneModeOn() {
		try {
			return Settings.System.getInt(
					getApplicationContext().getContentResolver(), 
					Settings.System.AIRPLANE_MODE_ON) == 1;
		} catch (SettingNotFoundException e) {
			Toast.makeText(this, e.getMessage(), 4000);
			return false;
		}
	}
	
	// Sets Airplane mode on or off
	private void setAirPlaneMode(boolean airPlaneModeOn) {
		// Set airplane mode
		Settings.System.putInt(
				getApplicationContext().getContentResolver(), 
				Settings.System.AIRPLANE_MODE_ON, airPlaneModeOn ? 1 : 0);

		// Post an intent to reload
		Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
		intent.putExtra("state", airPlaneModeOn);
		sendBroadcast(intent);		
	}
}
